/* 
 * Control Panel Functions
 * 
 */
var DEBUG = false;
var merchantsGrid;
var dealsGrid;
var usersGrid;
var categoriesGrid;
var categoriesGrid;
//client = new MappsieClient("www.dsforge.net/mappsie/index.php/api/","POST");
client = new MappsieClient("api/","GET");

function log(msg){
    if(DEBUG){
        try {
            console.log(msg);
        } catch(err){

        }
    }
}

function test(){
    
}

function getId(grid){
    return $('.trSelected td:first-child div', grid).text();
}

function processUserButtons(com,grid){
   var selected = getId(grid);
   
} 

Renderer = {
    populate            : function(form_id, obj){
        var formSelector = "#" + form_id;
        var form = $(formSelector);
        if(form){
            for(var i=0; i < obj.fields.length; i++ ){
                $(formSelector + " input[name=" + obj.fields[i] + "]").val(obj[obj.fields[i]]);
            }
        } else {
            alert(formSelector + " doesn't exist");
        }
    },
    /**
     {
           id: "countieslist",
           model: "county",
           text: "name",
           value: "id"
     }
     */
    populateSelect      : function(obj){
        var selSelector = "." + obj.id;
        var select = $(selSelector);
        var list = client.get({model: obj.model});
        select.append("<option value=''></option>");
        for(var i = 0; i < list.length; i++){
            select.append("<option value='" + list[i][obj.value] + "'>" + list[i][obj.text] + "</option>" );
        }
        
    }
    
};

Place = {
    insertPlace         : function(){
        var p = $("#newplaceform").serialize();
        
        try {
            
            if($("#newplaceform input[name=address]").val()==''){
                alert("Address cannot be empty");
                return;
            }

            var place = client.insert(p);

            if(place.id > 0){
                merchantsGrid.flexReload();
                $("#insert_place_dialog").dialog('close');
            } else {
                log(place);
            }
        } catch(err){
            log(err);
        }
        delete p;
    },
    editPlaceDialog     : function(){
        $("#edit_place_dialog").dialog('open');
        var _id = getId(merchantsGrid);
        $("#ep_id").val(_id);
        var merchant = client.get({model:"place", id: _id});
        Renderer.populate("editplaceform", merchant);
        $(".countieslist").val(merchant.county_id);
        $(".countieslist").trigger('change');
    },
    editPlace           : function(){
        var place = client.update($("#editplaceform").serialize());
        if(place.id > 0){
            merchantsGrid.flexReload();
            $("#edit_place_dialog").dialog('close');
        } else {
            alert("Server error. Please retry or contact administrator");
        }
    },
    newPlaceDialog      : function(){
        $("#insert_place_dialog").dialog('open');
    },
    deletePlace         : function(){
        var _id = getId(merchantsGrid);
        if(_id > 0){
            client.deleteObject({model: "Place", id: _id});
            merchantsGrid.flexReload();
        }
        
    }
}


Category = {
    insertCategory      : function(){
        var cat = $("#newcatform").serialize();
        var msg = client.insert(cat);
        
        if(msg.id > 0){
            categoriesGrid.flexReload();
            $("#insert_category_dialog").dialog('close');
            
        } else {
            alert("Error inserting category. Please try again or contact administrator.");
        }
    },
    newCategoryDialog      : function(){
        $("#insert_category_dialog").dialog('open');
        
    },
    editCategoryDialog      : function() {
        log("calling edit category");
        var _id = getId(categoriesGrid);
        var query = {model: "category", id: _id}
        Renderer.populate("updatecatform", client.get(query));
        $("#update_category_form").dialog('open');
    },
    updateCategory            : function(){
        var cat = $("#updatecatform").serialize();
        var c = client.update(cat);
        if(c.id > 0){
            $("#update_category_form").dialog('close');
            categoriesGrid.flexReload();
        }
    },
    deleteCategory : function(){
        var _id = getId(categoriesGrid);
        if(_id > 0){
            client.deleteObject({model: "Category", id: _id});
            categoriesGrid.flexReload();
        }
        
    }
    
};

User = {
    showDialog      : function(){
        $("#insert_user_dialog").dialog('open');
    },
    insertUser      : function() {
        try {
            var user = $("#newuserform").serialize();
            var newuser = client.insert(user);
            if(newuser.id > 0){
                $("#newuserform :input").val('');
                $("#insert_user_dialog").dialog('close');
                usersGrid.flexReload();
            } else {
                alert("Error connecting to the server. Please retry or contact administrator.");
            }
            
        } catch(err){
            log(err);
        }   
    },
    deleteUser      : function(){
        var _id = getId(usersGrid);
        if(_id > 0){
            var user = {
                id: _id, model: "user"
            }
            var msg = client.deleteObject(user);
            if(msg=="ok"){
                usersGrid.flexReload();
            } else {
                alert("Delete operation failed.");
            }
        } else {
            alert("Please select a user");
        }
    },
    updateUser              : function(){
        var user = $("#updateuserform").serialize();
        var u = client.update(user);
        if(u.id > 0){
            usersGrid.flexReload();
            $("#update_user_dialog").dialog('close');
        } else {
            alert("Update failed. Please retry or contact administrator.");
        }
    },
    showEditDialog          : function(){
        try {
            var _id = getId(usersGrid);
            Renderer.populate("updateuserform", client.getUser(_id));
            $("#update_user_dialog").dialog('open');
        } catch(err){
            log(err);
        }
        
    }
    
};

Deal = {
    
    insertDeal      : function(){
        var deal = $("#newdealform").serialize();
        
        try {
            client.insertDeal(deal);
            dealsGrid.flexReload();
            $("#insert_deal_dialog").dialog('close');
            
        } catch(err){
            log(err);
        }
    },
    newDealDialog   : function(com,grid){
        log("calling from Deal obj...");
        if(getId(merchantsGrid)>0){
            $("#nd_place_id").val(getId(merchantsGrid));
            $("#insert_deal_dialog").dialog('open');
        } else {
            alert("Please select a merchant for the deal");
        }    
    },
    showDeals       : function(com,grid){
            $("#dealstable").flexOptions(
            {
                url: "api/fg_getDealsForMerchant/?place_id=" + getId(grid),
                dataType:"json",
                method: "GET",
                colModel: [
                    {display: 'id',name:'id',sortable:false,width:50,align:'center'},
                    {display:"title", name:"title", sortable: true, width:150, align:'right'},
                    {display:'day of week',name:'day_of_week',sortable:false,width:60, align:'center'},
                    {display:'start time',name:'start_time',sortable: false, width: 60, alignt:'right'},
                    {display:'end time',name:'end_time',sortable: false, width: 60, alignt:'right'},
                    {display:'type',name:'type',sortable: false, width:100, align:'center'},
                    {display:'stock',name:'stock',sortable: false, width:100, align:'center'}
                ],
                buttons:[
                    {name: 'Add', bclass: 'add', onpress : Deal.insertDeal},
                    {name: 'Edit', bclass: 'edit', onpress : Deal.editDealDialog},
                    {name: 'Delete', bclass: 'delete', onpress : Deal.deleteDeal},
                    {separator: true}
                ],
                title: "Deals",
                usepager: true,
                userRp: true,
                singleSelect:true,
                searchItems: [{display:'title', name:'title'}]
            }
        ).flexReload();
    },
    editDealDialog  : function(){
        var _id = getId(dealsGrid);
        if(_id > 0){
            $("#ed_id").val(_id);
            var deal = client.get({
                model:"deal",
                id: _id
            });
            Renderer.populate("editdealform", deal);
            $("#edit_deal_dialog").dialog('open');
        } else {
            alert("Please choose a deal to edit.");
        }
        
    },
    editDeal        : function(){
        var deal = client.update($("#editdealform").serialize());
        if(deal.id > 0){
            $("#edit_deal_dialog").dialog('close');
            dealsGrid.flexReload();
        }
    },
    deleteDeal      : function (){
        var _id = getId(dealsGrid);
        if(_id > 0){
            client.deleteObject({model: "Deal", id: _id});
            dealsGrid.flexReload();
        }
    }
};



function processDealButtons(name){
    
}

function showDeals(com, grid){
    
    

}


$(document).ready(function(){
    log("ok...")
    //client = new MappsieClient();
    
    $("#tabs").tabs();
    
    /* populate selects */
    
    Renderer.populateSelect(
        {
           id: "countieslist",
           model: "county",
           text: "name",
           value: "id"
        }
    );
        
    Renderer.populateSelect(
        {
           id: "categorieslist",
           model: "category",
           text: "name",
           value: "id"
        }
    );
    
    $(".countieslist").change(
        function(){
            var select = $(".townslist");
            $(".townslist option").remove();
            try {
                var list = client.getTownsForCounty({
                    county_id: $(".countieslist").val()
                });
                
                for(var i = 0; i < list.length; i++){
                    var opt = list[i];
                    
                    var option = "<option value='" + opt.id + "'>" + opt.name + "</option>";
                    log(option);
                    select.append(option);
                }
            } catch(err){
                log(err);
            }
            
            
            
        }
    );
    
    /* end of selects */
    
    /* Dialogs */
    
    $("#insert_deal_dialog").dialog(
    {
        autoOpen:false, 
        title: "Insert Deal", 
        buttons:[
            {text: "Add", click: Deal.insertDeal},
            {text: "Cancel", click: function(){$("#insert_deal_dialog").dialog('close');}}
        ],
        modal: true
    }
    );
    
    $("#insert_user_dialog").dialog(
    {
       autoOpen: false,
       title: "Insert User",
       modal: true,
       buttons: [
           {text: "Add", click: User.insertUser},
           {text: "Cancel", click: function(){$("#insert_user_dialog").dialog('close');}}
       ]
    }
    );
       
    $("#insert_category_dialog").dialog(
    {
        autoOpen: false,
        title: "Insert Category",
        modal: true,
        buttons: [
            {text: "Add", click: Category.insertCategory},
            {text: "Cancel", click: function(){$("#insert_category_dialog").dialog('close');}}
        ]
       
    }
    );
        
    $("#update_user_dialog").dialog(
    {
        autoOpen: false,
        title: "Update User",
        modal: true,
        buttons: [
            {text: "Update", click: User.updateUser},
            {text: "Cancel", click: function(){$("#update_user_dialog").dialog('close');}}
        ]
    }
    );
        
    $("#update_category_form").dialog(
    {
        autoOpen:false,
        title: "Update Category",
        modal: true,
        buttons: [
            {text: "Update", click: Category.updateCategory},
            {text: "Cancel", click: function(){$("#update_category_form").dialog('close');}}
        
        ]
    }
    );
        
    $("#insert_place_dialog").dialog({
        autoOpen: false,
        title: "Insert place",
        modal: true,
        buttons : [
            {text: "Insert", click: Place.insertPlace},
            {text: "Cancel", click: function(){$("#insert_place_dialog").dialog('close');}}
        ]
    });
    
    $("#edit_deal_dialog").dialog(
    {
        autoOpen:false,
        title: "Edit deal",
        modal: true,
        buttons: [
            {text: "Edit", click: Deal.editDeal},
            {text: "Cancel", click: function(){$("#edit_deal_dialog").dialog('close');}}
        ]
    }
    );
        
    $("#edit_place_dialog").dialog(
    {
        autoOpen: false,
        title: "Edit Merchant",
        modal: true,
        buttons: [
            {text: "Update", click: Place.editPlace},
            {text: "Cancel", click: function(){$("#edit_place_dialog").dialog('close');}}
        ]
    }
    );
    
    
    
    /* end of Dialogs */
 
    try {
        usersGrid = $("#usertable").flexigrid(
            {
                url: "api/fg_getUsers/",
                dataType:"json",
                method: "GET",
                
                colModel: [
                    {display: 'id', name: 'id', sortable: true, width: 40, align:"center"},
                    {display: "fullname", name: 'fullname', width: 250, sortable: true, align:"right"},
                    {display: "mobile", name: 'mobile', sortable: false, width: 180, align:"right"},
                    {display: "email", name: 'email', sortable: false, width: 250, align:"right"}
                ],
                
                buttons : [
                    {name: 'Add User', bclass: 'add', onpress : User.showDialog},
                    {name: 'Edit Selected User', bclass: 'edit', onpress : User.showEditDialog},
                    {name: 'Delete Selected User', bclass: 'delete', onpress : User.deleteUser},
                    {separator: true}
                ],
                title: "Users",
                usepager: true,
                userRp: true,
                singleSelect:true,
                searchItems: [{display:'fullname', name:'fullname'}]

            }
        );
            
    
            
            
            
        merchantsGrid = $("#merchantstable").flexigrid(
            {
                url: "api/fg_getPlaces/",
                dataType:"json",
                method: "GET",
                
                colModel: [
                    {display: "id", name: "id", sortable: true, width: 40, align:"center"},
                    {display: "name", name: "name", width: 250, sortable: true, align:"right"},
                    {display: "address", name: "address", sortable: false, width: 180, align:"right"},
                    {display: "phone", name: "phone", sortable: false, width: 100, align:"right"},
                    {display: "email", name: "email", sortable: false, width: 100, align:"right"},
                    {display: "web", name: "web", sortable: false, width: 100, align:"right"},
                    {display: "category", name: "category_id", sortable: false, width: 50, align:"right"},
                    {display: "price rating", name: "price_rating", sortable: false, width: 50, align:"right"},
                ],
                
                buttons : [
                    {name: 'Add Place', bclass: 'add', onpress : Place.newPlaceDialog},
                    {name: 'Edit Place', bclass: 'edit', onpress : Place.editPlaceDialog},
                    {name: 'Delete', bclass: 'delete', onpress: Place.deletePlace },
                    {name: 'Show Deals', bclass: '', onpress : Deal.showDeals},
                    {separator: true}
                ],
                title: "Merchants / Places",
                usepager: true,
                userRp: true,
                singleSelect:true
                

            }
        );
        
        dealsGrid = $("#dealstable").flexigrid(
        {
            
            colModel: [
                    {display: 'id',name:'id',sortable:false,width:50,align:'center'},
                    {display:"title", name:"title", sortable: true, width:150, align:'right'},
                    {display:'day of week',name:'day_of_week',sortable:false,width:60, align:'center'},
                    {display:'start time',name:'start_time',sortable: false, width: 60, alignt:'right'},
                    {display:'end time',name:'end_time',sortable: false, width: 60, alignt:'right'},
                    {display:'type',name:'type',sortable: false,width:100, align:'center'},
                    {display:'stock',name:'stock',sortable: false,width:100, align:'center'}
            ],
            buttons:[
                {name: 'Add', bclass: 'add', onpress : Deal.newDealDialog},
                {name: 'Edit', bclass: 'edit', onpress : Deal.editDealDialog},
                {name: 'Delete', bclass: 'delete', onpress : Deal.deleteDeal},
                {separator: true}
            ],
            title: "Deals",
            usepager: true,
            userRp: true,
            searchItems: [{display:'title', name:'title'}]
        }
        );
        
        
        categoriesGrid = $("#categoriestable").flexigrid(
        {
            colModel: [
                {display: "id", name:"id",sortable:false, width: 50, align: 'center'},
                {display: "name", name:"name",sortable:true, width: 200, align: 'right'},
                {display: "bookable deals", name:"bookable_deals",sortable:false, width: 90, align: 'right'},
                {display: "drop in deals", name:"drop_in_deals",sortable:false, width: 90, align: 'right'},
                {display: "service locator", name:"service_locator",sortable:false, width: 90, align: 'right'},
                {display: "business directory", name:"business_directory",sortable:false, width: 90, align: 'right'}
            ],
            buttons : [
                {name: 'Add', bclass: 'add', onpress : Category.newCategoryDialog},
                {name: 'Edit', bclass: 'edit', onpress : Category.editCategoryDialog},
                {name: 'Delete', bclass: 'delete', onpress: Category.deleteCategory}
            ],
            title : "Categories",
            url: "api/fg_getTablePage/?model=category",
            dataType: "json",
            method: "GET",
            usepager: true,
            userRp: true,
            singleSelect:true
        }
        );
        
        if(DEBUG){
            $("#log_panel").dialog({
                title: "Log",
                modal:true,
                width: 450,
                height: 350

            });
        }
        
            
            
    } catch(err){
        log(err);
    }
    log("init finished...")
    
});

